$(function () {

    var socket = atmosphere; //获取socket
    var author = null;
    var transport = 'websocket';

    //配置一个websocket请求，实现一系列方法
    var request = {
        url: "/chat",
        contentType: "application/json",
        logLevel: 'debug',
        transport: transport,
        fallbackTransport: 'long-polling'
    };

    //打开连接执行的函数，初始化之后自动执行
    request.onOpen = function(response) {

        console.log("Atmosphere框架使用"+ response.transport+"方式连接")

        transport = response.transport;

        if (response.transport == "local") {
            subSocket.pushLocal("Name?");
        }
    };

    //重新连接执行的函数
    request.onReconnect = function(rq, rs) {
        console.log("重新连接")
    };

    //接受到一个服务端发送的消息
    request.onMessage = function(rs) {
        var message = rs.responseBody;
        try {
            var json = jQuery.parseJSON(message);
            console.log("收到了一个消息")
            console.log(json)
        } catch (e) {
            console.log('This doesn\'t look like a valid JSON object: ', message.data);
            return;
        }

        $('#panel').append(json.author+" "+"("+ json.time +")："+json.message+"<br />");


    };

    request.onClose = function(rs) {
        console.log("连接关闭")
    };

    request.onError = function(rs) {
       console.log("出现错误")
    };

    subSocket = socket.subscribe(request);

    $('#send').click(function () {
        var msg = $('#content').val();
        if (author == null) {
            author = msg;
        }

        var json = {
            author: author,
            message: msg
        };

        console.log("发送一条消息："+json)
        subSocket.push(jQuery.stringifyJSON(json));
    });

});

